package com.youlai.system.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.system.common.model.Option;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.entity.SysCourse;
import com.youlai.system.model.form.CategoryForm;
import com.youlai.system.model.query.CategoryPageQuery;
import com.youlai.system.model.vo.CategoryPageVO;
import com.youlai.system.model.vo.CategoryScoreCountVO;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.service.SysCategoryService;
import com.youlai.system.service.SysCourseService;
import com.youlai.system.service.SysScoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 故障分类控制器
 */
@Tag(name = "08.故障分类接口")
@RestController
@RequestMapping("/api/v1/categories")
@RequiredArgsConstructor
public class SysCategoryController {

    private final SysCategoryService categoryService;

    private final SysCourseService courseService;

    private final SysScoreService scoreService;

    @Operation(summary = "故障分类分页列表")
    @GetMapping("/page")
    public PageResult<CategoryPageVO> getCategoryPage(
            @ParameterObject CategoryPageQuery queryParams
    ) {
        IPage<CategoryPageVO> result = categoryService.getCategoryPage(queryParams);
        Map<Long, SysCourse> categoryCourseCountMap = courseService.getCategoryCourseCountMap();
        Map<Long, CategoryScoreCountVO> categoryScoreCountVOMap = scoreService.getAllCategoryScoreCountMap();
        result.getRecords().forEach(category -> {
            SysCourse course = categoryCourseCountMap.get(category.getId());
            if (course != null) {
                category.setCourseCount(course.getCourseCount());
                category.setGroupCourseName(course.getGroupCourseName());
            }
            CategoryScoreCountVO categoryScoreCountVO = categoryScoreCountVOMap.get(category.getId());
            if (categoryScoreCountVO != null) {
                category.setTotalCount(categoryScoreCountVO.getTotalCount());
                category.setSuccessCount(categoryScoreCountVO.getSuccessCount());
                category.setFailCount(categoryScoreCountVO.getFailCount());
                category.setSuccessRate(categoryScoreCountVO.getSuccessRate());
            }
        });
        return PageResult.success(result);
    }

    @Operation(summary = "新增故障分类")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:category:add')")
    @PreventDuplicateSubmit
    public Result saveCategory(
            @RequestBody @Valid CategoryForm categoryForm
    ) {
        boolean result = categoryService.saveCategory(categoryForm);
        return Result.judge(result);
    }

    @Operation(summary = "故障分类表单数据")
    @GetMapping("/{categoryId}/form")
    public Result<CategoryForm> getCategoryForm(
            @Parameter(description = "故障分类ID") @PathVariable Long categoryId
    ) {
        CategoryForm formData = categoryService.getCategoryForm(categoryId);
        return Result.success(formData);
    }


    @Operation(summary = "修改故障分类")
    @PutMapping(value = "/{categoryId}")
    @PreAuthorize("@ss.hasPerm('sys:category:edit')")
    public Result updateCategory(
            @Parameter(description = "故障分类ID") @PathVariable Long categoryId,
            @RequestBody @Validated CategoryForm categoryForm) {
        boolean result = categoryService.updateCategory(categoryId, categoryForm);
        return Result.judge(result);
    }

    @Operation(summary = "删除故障分类")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:category:delete')")
    public Result deleteCategories(
            @Parameter(description = "故障分类ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "故障分类删除数据为空");
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        boolean categoryHasUsed = courseService.categoryHasUsed(idList);
        Assert.isTrue(!categoryHasUsed, "故障分类使用中，不能被删除");
        boolean result = categoryService.deleteCategories(idList);
        return Result.judge(result);
    }

    @Operation(summary = "故障分类下拉列表")
    @GetMapping("/options")
    public Result<List<Option>> listCategoryOptions() {
        List<Option> list = categoryService.listCategoryOptions();
        return Result.success(list);
    }

}
